

package tomkitty;

import java.io.*;

public class TkHttpOutputStream extends OutputStream {

  protected OutputStream os;
  protected Response resp;
  protected boolean headersWritten = false;

  public TkHttpOutputStream(OutputStream os, Response resp) {
    this.os = os;
    this.resp = resp;
  }

  public void close() throws IOException {
    header();
    os.close();
  }

  public void flush() throws IOException {
    header();
    os.flush();
  }

  public void write(byte[] b) throws IOException {
    header();
    if (! resp.headersOnly()) {
      os.write(b);
    }
  }

  public void write(byte[] b, int off, int len) throws IOException {
    header();
    if (! resp.headersOnly()) {
      os.write(b, off, len);
    }
  }

  public void write(int b) throws IOException {
    header();
    if (! resp.headersOnly()) {
      os.write(b);
    }
  }

  public void header() throws IOException {
    if (!headersWritten) {
      Debug.d("Response: " + resp.getStatus() + "\n");
      if (resp.headersOnly()) {
        resp.setField("Content-Length", "0");
      }
      os.write(resp.getHeader().getBytes());
      headersWritten = true;
      resp.headerSent(true);
    }
  }

}

